package org.lagou.sqlSeesion;

import org.lagou.pojo.Configuration;
import org.lagou.pojo.MapperStatement;

import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    Map<String, Object> cacheMap = new HashMap<String, Object>();

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }


    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {

        // go to Executor
        List<Object> list = new ArrayList<>();
        simpleExecutor simpleExecutor = new simpleExecutor();
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
        if(cacheMap.get(statementId) == null) {
            list = simpleExecutor.query(configuration, mapperStatement, params);
            cacheMap.put(statementId, list);
        }else {
            System.out.println("从缓存中取出数据！");
            return (List<E>) cacheMap.get(statementId);
        }
        return (List<E>) list;

    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {

        List<Object> objects = selectList(statementId, params);
        if(objects.size() == 1) {
            return (T) objects.get(0);
        }else {
            throw new RuntimeException("select one but too many results");
        }

    }

    @Override
    public Object doUpdate(String statementId, Object... params) throws Exception {
        simpleExecutor simpleExecutor = new simpleExecutor();
        MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
        int result = simpleExecutor.doUpdate(configuration, mapperStatement, params);
        cacheMap.clear();
        return result;
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {

        // 使用JDK动态代理来为Dao接口生成代理对象，并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // proxy 当前代理对象的引用
                // method 当前被调用的方法的引用
                // args 传递的参数
                // 底层还是JDBC的调用 // 也可以根据不同情况，调用selectOne或者selectList
                // invoke方法中无法获得配置文件中的namespace.id，因此namespace使用接口全限定名，id使用方法名，来保持一致
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();

                String statementId = className + "." + methodName;

                // 准备参数 params:args
                // 获取被调用方法的返回值类型
                Type genericReturnType = method.getGenericReturnType();
                String type = genericReturnType.getTypeName();
                // 判断是否进行了泛型类型参数化
                if (genericReturnType instanceof ParameterizedType) {
                    List<Object> objects = selectList(statementId, args);
                    return objects;
                }else if("int".equals(type)) {
                    return doUpdate(statementId, args);
                }else {
                    return selectOne(statementId, args);
                }

            }
        });

        return (T) proxyInstance;
    }

    @Override
    public <T> T getMapperOrderBy(Class<?> mapperClass, String orderField) {

        // 使用JDK动态代理来为Dao接口生成代理对象，并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                // proxy 当前代理对象的引用
                // method 当前被调用的方法的引用
                // args 传递的参数
                // 底层还是JDBC的调用 // 也可以根据不同情况，调用selectOne或者selectList
                // invoke方法中无法获得配置文件中的namespace.id，因此namespace使用接口全限定名，id使用方法名，来保持一致
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();

                String statementId = className + "." + methodName;

                // 准备参数 params:args
                // 获取被调用方法的返回值类型
                Type genericReturnType = method.getGenericReturnType();
                String type = genericReturnType.getTypeName();
                // 判断是否进行了泛型类型参数化
                if (genericReturnType instanceof ParameterizedType) {

                    MapperStatement mapperStatement = configuration.getMapperStatementMap().get(statementId);
                    mapperStatement.setSql(mapperStatement.getSql() + " order by " + orderField + " desc ");

                    List<Object> objects = selectList(statementId, args);
                    return objects;
                }else {
                    throw new Exception("该方法不允许使用排序接口");
                }

            }
        });

        return (T) proxyInstance;
    }
}
